/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.database.tables;

import com.chipchip.database.DBManager;
import com.chipchip.database.objects.DOObstacle;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 *
 * @author Tri
 */
public class DTObstacle {
    private static DTObstacle instance = null;
    public static DTObstacle sharedInstance() {
        if(instance == null) {
            instance = new DTObstacle();
        }
        return instance;
    }
    public static final String TABLE_NAME = "Obstacle";
    private MongoOperations m_mongoOperations;
    
    private DTObstacle() {
        m_mongoOperations = DBManager.sharedInstance().mongoOperations();
    }
    
    public DOObstacle select(String obsID) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOObstacle.KEY_ID).is(obsID));
        return m_mongoOperations.findOne(query, DOObstacle.class);
    }
    
    public void insert(DOObstacle obj) {
        m_mongoOperations.save(obj, TABLE_NAME);
    }
    
    public boolean delete(String obsID) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOObstacle.KEY_ID).is(obsID));
        DOObstacle result = m_mongoOperations.findOne(query, DOObstacle.class);
        if(result != null) {
            m_mongoOperations.remove(obsID);
            return true;
        }
        return false;
    }
    
    public boolean update(DOObstacle obs) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOObstacle.KEY_ID).is(obs.getID()));
        DOObstacle result = m_mongoOperations.findOne(query, DOObstacle.class);
        if(result != null) {
            Update update = new Update();
            update.set(DOObstacle.KEY_DES, obs.desc);
            update.set(DOObstacle.KEY_IMG_URL, obs.imageURL);
            update.set(DOObstacle.KEY_NAME, obs.name);
            
            m_mongoOperations.updateFirst(query, update, DOObstacle.class);
            return true;
        }
        return false;
    }
}
